<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Env;

class Index extends Controller
{
    public function index(Request $request)
    {
        $page = $request->param('apage') or 1;//当前的页码

        // 1、找出所有图书类别
        $bclass = Db::table('book')->distinct('ture')->field('bclass')->select();
        $this->assign('bclasses',$bclass);
        
        
        //2、筛选条件
        $bname = $request->param('bname');
        $bcls = $request->param('bclass');
        $searchstr = 'true ';
        if (!empty($bcls) && strcmp('不限', $bcls)){
            $searchstr.="and bclass='".$bcls."'";
        }
        if (!empty($bname)){
            $searchstr.=" and bname like '%".$bname."%'";
        }

        //3、通过条件分页查询        
        $data = Db::table('book')->where($searchstr)->order('SelledNum','desc')->paginate(12,false, [
            'type' => 'Bootstrap',
            'var_page' => 'page',
            'path' => 'javascript:AjaxPage([PAGE]);',
            'page' => $page, //设置当前页
        ]);

        //整数部分和小数部分分离
        for($i = 0 ;$i<count($data);$i++){
            $smallprice = $data[$i]['yourprice'] - floor($data[$i]['yourprice']);
            /* if($smallprice < 10){
                $smallprice = '0'.$smallprice;
            } */
            $smallprice *= 100;
            $data[$i] = array_merge($data[$i], ['smallprice'=>floor($smallprice)]);
            $data[$i] =array_merge($data[$i], ['yourprice'=>floor($data[$i]['yourprice'])]);
        }
        // dump($data);

        $this->assign('books',$data);
        $page=$data->render();
        $this->assign('page',$page);


        //过滤---如果是ajax请求，直接返回请求的数据
        $rootpath = Env::get('rootpath', '/bookTP');
        if($request->isAjax()){
            //将书本显示的内容组织起来
            $html = "";
            foreach($data->toArray()['data'] as $book){
               $str = <<<html
               <div class="shopBox">
               <a href="{$rootpath}/index/shopdetail/shopdetail?bookID={$book['bookID']}">
                    <img src="{$rootpath}/public/static/image/{$book['pictures']}" alt=""></a>
                <p class="describe">{$book['bname']}</p>
                <p class="price">￥</p>
                <p class="price intnum">{$book['yourprice']}</p>
                <!--整数部分-->
                <p class="price">.{$book['smallprice']}元</p>
                <!--小数部分-->
                <span class="selledNum">销量: {$book['SelledNum']}</span>
                <a href='{$rootpath}/index/cart/addCart?bookID={$book["bookID"]}'>
                    <span class="toCart" onclick="toCart('{$book["bookID"]}')">&#xf217</span></a>
            </div>
html;
                $html .= $str;
            }
            $result = ['html' => $html, 'page' => $page];
            return json($result); //返回json格式的数据
        }
        
        return $this->fetch();
    }
    
}
